<template>
  <view class="profile-container">
    <!-- 用户信息头部 -->
    <view class="user-header">
      <view class="user-info">
        <image :src="userInfo.avatar" class="avatar" mode="aspectFit" />
        <view class="user-detail">
          <text class="username">{{ userInfo.username }}</text>
          <text class="welcome">欢迎来到图书商城</text>
        </view>
      </view>
      <text class="settings-btn" @click="goToSettings">⚙️</text>
    </view>

    <!-- 主要内容区域 -->
    <scroll-view scroll-y class="content-scroll" :style="{ height: scrollViewHeight + 'px' }">
      <!-- 购物车统计 -->
      <view class="stats-section">
        <view class="stats-grid">
          <view class="stat-item" @click="goToCart">
            <text class="stat-number">{{ cartTotalCount }}</text>
            <text class="stat-label">购物车</text>
          </view>
          <view class="stat-item" @click="goToOrderList('pending')">
            <text class="stat-number">{{ pendingOrderCount }}</text>
            <text class="stat-label">待付款</text>
          </view>
          <view class="stat-item" @click="goToOrderList('shipping')">
            <text class="stat-number">{{ shippingOrderCount }}</text>
            <text class="stat-label">待发货</text>
          </view>
          <view class="stat-item" @click="goToOrderList('completed')">
            <text class="stat-number">{{ completedOrderCount }}</text>
            <text class="stat-label">已完成</text>
          </view>
        </view>
      </view>

      <!-- 订单状态 -->
      <view class="order-section">
        <view class="section-header" @click="goToOrderList">
          <text class="section-title">我的订单</text>
          <text class="more">查看全部 ></text>
        </view>
        
        <view class="order-status">
          <view class="status-item" @click="goToOrderList('pending')">
            <image src="/static/order-pending.png" class="status-icon" mode="aspectFit" />
            <text class="status-text">待付款</text>
          </view>
          <view class="status-item" @click="goToOrderList('shipping')">
            <image src="/static/order-shipping.png" class="status-icon" mode="aspectFit" />
            <text class="status-text">待发货</text>
          </view>
          <view class="status-item" @click="goToOrderList('delivered')">
            <image src="/static/order-delivered.png" class="status-icon" mode="aspectFit" />
            <text class="status-text">待收货</text>
          </view>
          <view class="status-item" @click="goToOrderList('completed')">
            <image src="/static/order-completed.png" class="status-icon" mode="aspectFit" />
            <text class="status-text">已完成</text>
          </view>
          <view class="status-item" @click="goToOrderList('after_sale')">
            <image src="/static/order-aftersale.png" class="status-icon" mode="aspectFit" />
            <text class="status-text">售后</text>
          </view>
        </view>
      </view>

      <!-- 功能菜单 -->
      <view class="menu-section">
        <view class="menu-item" @click="goToCart">
          <view class="menu-left">
            <image src="/static/icon-cart.png" class="menu-icon" mode="aspectFit" />
            <text class="menu-text">购物车</text>
          </view>
          <view class="menu-right">
            <text class="cart-count" v-if="cartCount > 0">{{ cartCount > 99 ? '99+' : cartCount }}件商品</text>
            <text class="arrow">></text>
          </view>
        </view>
        
        <view class="menu-item" @click="goToBookshelf">
          <view class="menu-left">
            <image src="/static/icon-bookshelf.png" class="menu-icon" mode="aspectFit" />
            <text class="menu-text">我的书架</text>
          </view>
          <view class="menu-right">
            <text class="unread-count" v-if="unreadCount > 0">{{ unreadCount > 99 ? '99+' : unreadCount }}本未读</text>
            <text class="arrow">></text>
          </view>
        </view>
        
        <view class="menu-item" @click="goToCollection">
          <view class="menu-left">
            <image src="/static/icon-collection.png" class="menu-icon" mode="aspectFit" />
            <text class="menu-text">我的收藏</text>
          </view>
          <text class="arrow">></text>
        </view>
        
        <view class="menu-item" @click="goToAddress">
          <view class="menu-left">
            <image src="/static/icon-address.png" class="menu-icon" mode="aspectFit" />
            <text class="menu-text">收货地址</text>
          </view>
          <text class="arrow">></text>
        </view>
        
        <view class="menu-item" @click="goToCustomerService">
          <view class="menu-left">
            <image src="/static/icon-service.png" class="menu-icon" mode="aspectFit" />
            <text class="menu-text">客服中心</text>
          </view>
          <text class="arrow">></text>
        </view>
        
        <view class="menu-item" @click="goToAbout">
          <view class="menu-left">
            <image src="/static/icon-about.png" class="menu-icon" mode="aspectFit" />
            <text class="menu-text">关于我们</text>
          </view>
          <text class="arrow">></text>
        </view>
      </view>

      <!-- 退出登录 -->
      <view class="logout-section">
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </view>
      
      <!-- 底部占位区域 -->
      <view class="bottom-placeholder" :style="{ height: placeholderHeight + 'px' }"></view>
    </scroll-view>

    <!-- 底部导航栏 -->
    <view class="tab-bar">
      <view 
        v-for="tab in tabList" 
        :key="tab.pagePath"
        class="tab-item"
        :class="{ active: currentTab === tab.pagePath }"
        @click="switchTab(tab)"
      >
        <view class="tab-icon">
          <image 
            :src="currentTab === tab.pagePath ? tab.selectedIconPath : tab.iconPath" 
            class="icon"
            mode="aspectFit"
          />
          <!-- 书架角标 -->
          <view v-if="tab.pagePath === 'bookshelf' && unreadCount > 0" class="bookshelf-badge">
            <text class="badge-text">{{ unreadCount > 99 ? '99+' : unreadCount }}</text>
          </view>
        </view>
        <text class="tab-text">{{ tab.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {
        username: '图书爱好者',
        avatar: '/static/avatar-default.png'
      },
      cartCount: 0,
      cartTotalCount: 0,
      pendingOrderCount: 0,
      shippingOrderCount: 0,
      completedOrderCount: 0,
      unreadCount: 0,
      scrollViewHeight: 0,
      placeholderHeight: 0,
      
      // 底部导航相关数据 - 保持原样，一个字都不动
      currentTab: 'profile',
      tabList: [
        {
          pagePath: 'index',
          text: '首页',
          iconPath: '/static/tabbar/home.png',
          selectedIconPath: '/static/tabbar/home-active.png'
        },
        {
          pagePath: 'category',
          text: '分类',
          iconPath: '/static/tabbar/category.png',
          selectedIconPath: '/static/tabbar/category-active.png'
        },
        {
          pagePath: 'bookshelf',
          text: '书架',
          iconPath: '/static/tabbar/bookshelf.png',
          selectedIconPath: '/static/tabbar/bookshelf-active.png'
        },
        {
          pagePath: 'profile',
          text: '我的',
          iconPath: '/static/tabbar/profile.png',
          selectedIconPath: '/static/tabbar/profile-active.png'
        }
      ]
    }
  },
  onLoad() {
    this.calcLayoutHeight()
    this.loadUserInfo()
    this.updateCartStats()
    this.updateBookshelfStats()
  },
  onShow() {
    this.updateCartStats()
    this.updateBookshelfStats()
    this.updateBookshelfBadge()
  },
  onResize() {
    this.calcLayoutHeight()
  },
  methods: {
    // 计算布局高度
    calcLayoutHeight() {
      const systemInfo = uni.getSystemInfoSync()
      const windowHeight = systemInfo.windowHeight
      const tabBarHeight = 100 // 底部导航栏高度
      const headerHeight = 200 // 头部高度
      
      // 内容区域高度 = 窗口高度 - 头部高度 - 底部导航栏高度
      this.scrollViewHeight = windowHeight - headerHeight - tabBarHeight
      
      // 占位区域高度 = 底部导航栏高度 + 安全区域底部间距
      this.placeholderHeight = tabBarHeight + (systemInfo.safeAreaInsets?.bottom || 0)
    },
    
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
      }
    },

    updateCartStats() {
      const cart = uni.getStorageSync('cart') || []
      const orders = uni.getStorageSync('orders') || []
      
      // 购物车统计
      this.cartCount = cart.reduce((sum, item) => sum + item.quantity, 0)
      this.cartTotalCount = cart.length
      
      // 订单统计
      this.pendingOrderCount = orders.filter(order => order.status === 'pending').length
      this.shippingOrderCount = orders.filter(order => order.status === 'shipping').length
      this.completedOrderCount = orders.filter(order => order.status === 'completed').length
    },

    updateBookshelfStats() {
      const bookshelf = uni.getStorageSync('bookshelf') || []
      this.unreadCount = bookshelf.filter(book => book.status === 'unread').length
    },

    updateBookshelfBadge() {
      if (this.unreadCount > 0) {
        uni.setTabBarBadge({
          index: 2, // 书架在tabbar的索引位置
          text: this.unreadCount > 99 ? '99+' : this.unreadCount.toString()
        })
      } else {
        uni.removeTabBarBadge({ index: 2 })
      }
    },

    goToSettings() {
      uni.navigateTo({
        url: '/pages/settings/settings'
      })
    },

    goToCart() {
      uni.navigateTo({
        url: '/pages/cart/cart'
      })
    },

    goToBookshelf() {
      uni.switchTab({
        url: '/pages/bookshelf/bookshelf'
      })
    },

    goToOrderList(status = '') {
      uni.navigateTo({
        url: `/pages/order/list?status=${status}`
      })
    },

    goToCollection() {
      uni.navigateTo({
        url: '/pages/collection/collection'
      })
    },

    goToAddress() {
      uni.navigateTo({
        url: '/pages/address/address'
      })
    },

    goToCustomerService() {
      uni.navigateTo({
        url: '/pages/service/service'
      })
    },

    goToAbout() {
      uni.navigateTo({
        url: '/pages/about/about'
      })
    },

    handleLogout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            uni.showToast({ title: '退出成功', icon: 'success' })
            
            setTimeout(() => {
              uni.redirectTo({ url: '/pages/login/login' })
            }, 1500)
          }
        }
      })
    },

    // 底部导航切换方法
    switchTab(tab) {
      if (this.currentTab === tab.pagePath) return
      
      const pageMap = {
        'index': '/pages/index/index',
        'category': '/pages/category/category',
        'bookshelf': '/pages/bookshelf/bookshelf',
        'profile': '/pages/profile/profile'
      }
      
      const targetUrl = pageMap[tab.pagePath]
      if (targetUrl) {
        uni.switchTab({
          url: targetUrl,
          fail: (err) => {
            console.error('跳转失败:', err)
            uni.redirectTo({
              url: targetUrl
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.user-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx;
  background: linear-gradient(135deg, #007AFF, #5AC8FA);
  color: #fff;
  height: 200rpx;
  box-sizing: border-box;
  flex-shrink: 0;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 50%;
  border: 4rpx solid rgba(255,255,255,0.3);
  margin-right: 30rpx;
}

.user-detail {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.welcome {
  font-size: 24rpx;
  opacity: 0.9;
}

.settings-btn {
  font-size: 40rpx;
  padding: 20rpx;
}

.content-scroll {
  flex: 1;
  overflow: hidden;
}

.stats-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 15rpx;
  overflow: hidden;
  padding: 30rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
}

.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

.order-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 15rpx;
  overflow: hidden;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.more {
  font-size: 26rpx;
  color: #666;
}

.order-status {
  display: flex;
  justify-content: space-around;
  padding: 30rpx 0;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 15rpx;
}

.status-text {
  font-size: 24rpx;
  color: #333;
}

.menu-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 15rpx;
  overflow: hidden;
}

.menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.menu-left {
  display: flex;
  align-items: center;
}

.menu-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
}

.menu-text {
  font-size: 28rpx;
  color: #333;
}

.menu-right {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.cart-count {
  font-size: 24rpx;
  color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.unread-count {
  font-size: 24rpx;
  color: #ff6b6b;
  background: rgba(255, 107, 107, 0.1);
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
}

.arrow {
  color: #999;
  font-size: 28rpx;
}

.logout-section {
  padding: 40rpx 20rpx;
}

.logout-btn {
  background: #fff;
  color: #FF3B30;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 32rpx;
  border: none;
  width: 100%;
}

.bottom-placeholder {
  width: 100%;
}

/* 底部导航栏样式 */
.tab-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  z-index: 999;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  position: relative;
  
  &.active {
    .tab-text {
      color: #ff6b6b;
    }
  }
}

.tab-icon {
  position: relative;
  margin-bottom: 8rpx;
}

.icon {
  width: 44rpx;
  height: 44rpx;
  display: block;
}

.bookshelf-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: #ff6b6b;
  border-radius: 20rpx;
  min-width: 30rpx;
  height: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

.badge-text {
  color: #fff;
  font-size: 20rpx;
  line-height: 1;
}

.tab-text {
  font-size: 22rpx;
  color: #666;
}
</style>